<script setup lang="ts">
import { computed, reactive, ref, watch } from 'vue';
import { usePagination } from '@sa/alova/client';
import { $t } from '@/locales';
import { useNaiveForm } from '@/hooks/common/form';
import useTableOperate from '@/hooks/common/table/table-operate';
import useCheckedColumns from '@/hooks/common/table/table-columns';
import { createCodeTable, paginateDbTable } from '@/service/api/dev/code/code-table';

defineOptions({
  name: 'CodeTableAddDrawer'
});

interface Emits {
  (e: 'submitted'): void;
}

const emit = defineEmits<Emits>();

const visible = defineModel<boolean>('visible', {
  default: false
});

const title = computed(() => {
  return '添加表';
});

const searchParams = reactive({
  dbId: null,
  name: null,
  comment: null
});

const submitting = ref<boolean>(false);
const initialParams = { ...searchParams };
const { formRef } = useNaiveForm();

const { loading, data, page, pageSize, pageCount, send, remove } = usePagination(
  (p, sz) =>
    paginateDbTable({
      ...searchParams,
      pageNumber: p,
      pageSize: sz
    }),
  {
    data: ({ records }) => records,
    total: ({ total }) => total,
    watchingStates: [searchParams],
    debounce: [500]
  }
);

const { checkedRowKeys } = useTableOperate(data, {
  async delete(row) {
    // await deleteCodeTable({ id: row.id });
    remove(row);
  },
  async batchDelete(rows) {
    // await batchDelCodeTable({ ids: rows.map(row => row.id) });
    remove(...rows);
  }
});

const { columns } = useCheckedColumns<typeof paginateDbTable>(() => [
  {
    type: 'selection',
    align: 'center',
    width: 48
  },
  {
    key: 'name',
    title: '表名称',
    align: 'center',
    width: 100
  },
  {
    key: 'comment',
    title: '表描述',
    align: 'center',
    width: 100
  }
]);

const paginationConfig = computed(() => ({
  page: page.value,
  pageSize: pageSize.value,
  showSizePicker: true,
  pageCount: pageCount.value,
  pageSizes: [10, 15, 20, 25, 30],
  onUpdatePage: (value: number) => {
    page.value = value;
  },
  onUpdatePageSize: (value: number) => {
    pageSize.value = value;
  }
}));

const searchPaginate = (newPage = 1) => {
  page.value = newPage;
  send(page.value, pageSize.value);
};

function closeDrawer() {
  visible.value = false;
}

async function handleSubmit() {
  console.log(checkedRowKeys.value);

  // checkedRowKeys.value.forEach(col => {
  //   console.log(col.key, col.checked);
  // });
  const tables: string[] = [];
  checkedRowKeys.value.forEach(id => {
    tables.push(id as string);
  });

  console.log(searchParams.dbId, tables);

  await createCodeTable({
    dbId: searchParams.dbId,
    tableNames: tables
  });

  // checkedRowKeys.value
  // data.value.find(item => item.id === id)

  // request
  // await submit();
  window.$message?.success($t('common.updateSuccess'));
  closeDrawer();
  emit('submitted');
}

watch(visible, () => {
  if (visible.value) {
    reset();
  }
});

async function search() {
  searchPaginate(page.value);
}

async function reset() {
  Object.assign(searchParams, initialParams);

  checkedRowKeys.value = [];
}
</script>

<template>
  <NDrawer v-model:show="visible" display-directive="show" width="800">
    <NDrawerContent :title="title" :native-scrollbar="false" closable>
      <NForm ref="formRef" :model="searchParams" label-placement="left" :label-width="80">
        <NGrid responsive="screen" item-responsive>
          <NFormItemGi span="24 s:12" label="数据源" path="dbId" class="pr-24px">
            <PorSelect
              v-model:value="searchParams.dbId"
              placeholder="请选择数据源"
              url="/dev/code/codeDb/simpleList"
              label-field="name"
              value-field="id"
              value-to-number
              filterable
              class="user-select"
              size="small"
              clearable
            ></PorSelect>
          </NFormItemGi>
          <NFormItemGi span="24 s:12" label="表名称" path="name" class="pr-24px">
            <NInput v-model:value="searchParams.name" placeholder="表名称" clearable />
          </NFormItemGi>
          <NFormItemGi span="24 s:12" label="表描述" path="comment" class="pr-24px">
            <NInput v-model:value="searchParams.comment" placeholder="表描述" clearable />
          </NFormItemGi>
          <NFormItemGi span="24 s:12 m:6">
            <NSpace class="w-full" justify="end">
              <NButton @click="reset">
                <template #icon>
                  <icon-ic-round-refresh class="text-icon" />
                </template>
                {{ $t('common.reset') }}
              </NButton>

              <NButton type="primary" ghost @click="search">
                <template #icon>
                  <icon-ic-round-search class="text-icon" />
                </template>
                {{ $t('common.search') }}
              </NButton>
            </NSpace>
          </NFormItemGi>
        </NGrid>
      </NForm>

      <NCard title="数据库表" :bordered="false" size="small" class="sm:flex-1-hidden card-wrapper">
        <NDataTable
          v-model:checked-row-keys="checkedRowKeys"
          :columns="columns"
          :data="data"
          size="small"
          :loading="loading"
          remote
          :row-key="row => row.id"
          :pagination="paginationConfig"
          class="sm:h-full"
        />
      </NCard>
      <template #footer>
        <NSpace :size="16">
          <NButton @click="closeDrawer">{{ $t('common.cancel') }}</NButton>
          <NButton type="primary" :loading="submitting" @click="handleSubmit">{{ $t('common.confirm') }}</NButton>
        </NSpace>
      </template>
    </NDrawerContent>
  </NDrawer>
</template>

<style scoped></style>
